/**
 * @file
 * @author dousha 
 * @date 2021/5/16.
 */

#include "blinker.h"

static uint8_t state = 0, period = 0;
static uint32_t nextActionTime = 0;
static GPIO_TypeDef *rank;
static uint16_t pin;

static void blinker_make() {
	HAL_GPIO_WritePin(rank, pin, GPIO_PIN_RESET);
}

static void blinker_break() {
	HAL_GPIO_WritePin(rank, pin, GPIO_PIN_SET);
}

void blinker_init(GPIO_TypeDef *r, uint16_t p) {
	state = 0;
	rank = r;
	pin = p;
}

void blinker_tick() {
	if (state) {
		if (HAL_GetTick() >= nextActionTime) {
			if (state == 1) {
				state = 2;
				blinker_make();
			} else {
				state = 1;
				blinker_break();
			}
			nextActionTime += period * 100;
		}
	}
}

void blinker_on() {
	state = 0;
	blinker_make();
}

void blinker_off() {
	state = 0;
	blinker_break();
}

void blinker_blink(uint8_t p) {
	period = p;
	state = 1;
	nextActionTime = HAL_GetTick() + 100 * period;
}
